package com.game.game.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.game.message.protocol.ProtocolsConfig;

public class CharUtil {
	
	public static int checkNameValid(String name) {
		int nameLength = 0;
		for (int i = 0; i < name.length(); i++) {
			if (!isRightChar(name.charAt(i))) return ProtocolsConfig.INVALID_NAME_CHAR;
			if (isChinese(name.charAt(i))) nameLength += 2;
			else if (isWord(name.charAt(i))) nameLength += 1;
		}
		if (nameLength <= 6 || nameLength >= 12) {
			return ProtocolsConfig.INVALID_NAME_LENGTH;
		}
		return ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS;
	}
	
	/**
     * 验证是否是汉字或者0-9、a-z、A-Z
     * 
     * @param c
     *            被验证的char
     * @return true代表符合条件
     */
    public static boolean isRightChar(char c) {
        return isChinese(c) || isWord(c);
    }
    
    /**
     * 校验某个字符是否是a-z、A-Z、_、0-9
     * 
     * @param c
     *            被校验的字符
     * @return true代表符合条件
     */
    public static boolean isWord(char c) {
        String regEx = "[\\w]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher("" + c);
        return m.matches();
    }
    
    /**
     * 判定输入的是否是汉字
     * 
     * @param c
     *            被校验的字符
     * @return true代表是汉字
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
}
